<?php

namespace App\Admin\Forms\Settings;

use App\Handlers\ImageUploadHandler;
use App\Models\Setting;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class Basic extends Form
{
    /**
     * The form title.
     *
     * @var string
     */
    public $title = '基本';

    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|mixed
     * @throws \Exception
     */
    public function handle(Request $request)
    {
        $post = $request->basic;

        try {
            if (isset($post['site_logo']) && $file = $post['site_logo']) {
                $uploader = new ImageUploadHandler();
                $result = $uploader->save($file, 'settings', 'logo', 200);
                if ($result) {
                    $post['site_logo'] = $result['path'];
                }
            } else {
                $sites = \Illuminate\Support\Facades\Cache::get('showcj.settings.basic');
                $post['site_logo'] = isset($sites['site_logo']) ? $sites['site_logo'] : '';
            }
        } catch (\Exception $e) {
            admin_error($e->getMessage());
            return back();
        }


        $basic = json_encode($post, JSON_UNESCAPED_UNICODE);
        Setting::query()->updateOrCreate(['name' => 'basic'], ['value' => $basic]);

        Cache::forever('showcj.settings.basic', $post);

        admin_success('操作成功');

        return back();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->text('basic.site_name', '网站标题')->required()->help("调用方式：config('site_title')");
        $this->text('basic.site_slogan', '网站标语')->required()->help("站点口号，调用方式：config('site_slogan')");
        $this->image('basic.site_logo', '网站logo')->options(['language' => 'zh']);
        $this->text('basic.seo_keywords', '站点关键词')->help('SEO 网站搜索引擎关键字');
        $this->textarea('basic.seo_description', '站点描述')->help('SEO 网站描述，有利于搜索引擎抓取相关信息');
        $this->text('basic.site_copyright', '版权信息')->help("调用方式：config('site_copyright')");
        $this->text('basic.site_icp', '备案信息')->help("调用方式：config('site_icp')");
        $this->textarea('basic.site_statistics', '网站统计代码')->rows(8)
            ->help("网站统计代码，支持百度、Google、cnzz等，调用方式：config('site_statistics')");
    }

    /**
     * The data of the form.
     *
     * @return array $data
     */
    public function data()
    {
        $data = Setting::query()->where('name', 'basic')->value('value');
        $data = empty($data) ? [] : json_decode($data, true);

        return [
            'basic' => $data

        ];
    }
}
